package com.eascs.web.p2p.member.controller;

import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.p2p.common.entity.InvestorBankEntity;
import com.eascs.p2p.common.entity.InvestorEntity;
import com.eascs.p2p.common.entity.InvestorWalletEntity;
import com.eascs.p2p.common.entity.InvestorWalletFlowEntity;
import com.eascs.p2p.common.investor.service.InvestorBankService;
import com.eascs.p2p.common.security.MD5;
import com.eascs.p2p.common.service.ISelectDataService;
import com.eascs.p2p.common.service.InvestorService;
import com.eascs.p2p.common.vo.ModelResult;
import com.eascs.p2p.common.wallet.service.InvestorWalletService;
import com.eascs.site.view.ViewContext;
import com.eascs.web.p2p.common.controller.BaseMasterViewController;
import com.eascs.web.p2p.common.entity.vo.PageResultVO;
import com.eascs.web.p2p.member.untils.BankCardUtils;
import com.eascs.web.p2p.pay.service.YeePayService;

@RequestMapping("/member")
@Controller
public class UserController extends BaseMasterViewController {
	private final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Reference
	InvestorService investorService;
	@Reference
	InvestorWalletService investorWalletService;
	@Reference
	ISelectDataService selectDataService;
	@Autowired
	LoginRestController loginRestController;
	@Autowired
	YeePayService yeePayService;
	@Reference
	InvestorBankService investorBankService;

	@RequestMapping(value = "/financial/details")
	public String financialDetails(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		InvestorEntity investor = modelResult.getModel();
		ViewContext.put("investorId", investor.getId());
		return "/investor/financialDetails";
	}

	@RequestMapping(value = "/investrecord")
	public String investRecord(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		return "/investor/investRecord";
	}

	@RequestMapping(value = "/ftl/set")
	public String settings(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		InvestorEntity investor = modelResult.getModel();
		ViewContext.put("investor", investor);
		return "/member/set";
	}

	@RequestMapping(value = "/ftl/pay")
	public String pay(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		InvestorEntity investor = modelResult.getModel();
		ModelResult<InvestorBankEntity> investorBankMR = investorBankService.queryInvestorBankById(investor.getBankRequestno());
		InvestorBankEntity investorBank = investorBankMR.getModel();
		if (StringUtils.isNotBlank(investorBank.getBankNo())) {
			String bankNo = BankCardUtils.closedCardNum(investorBank.getBankNo());
			ViewContext.put("bankNo", bankNo);
		}
		ViewContext.put("investor", investor);
		ModelResult<InvestorWalletEntity> wallet = investorWalletService.queryInvestorWallet(investor.getId());
		if (wallet.isSuccess() && wallet.getModel() != null) {
			ViewContext.put("wallet", wallet.getModel());
		}
		return "/member/pay";
	}
	
	@RequestMapping(value = "/ftl/withdraw")
	public String withdraw(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		InvestorEntity investor = modelResult.getModel();
		ModelResult<InvestorBankEntity> investorBankMR = investorBankService.queryInvestorBankById(investor.getBankRequestno());
		InvestorBankEntity investorBank = investorBankMR.getModel();
		if (investorBank == null ) {
			return "redirect:/login/index";
		}
		String bankNo = BankCardUtils.closedCardNum(investorBank.getBankNo());
		ViewContext.put("investor", investor);
		ViewContext.put("bankNo", bankNo);
		ModelResult<InvestorWalletEntity> wallet = investorWalletService.queryInvestorWallet(investor.getId());
		if (wallet.isSuccess() && wallet.getModel() != null) {
			ViewContext.put("wallet", wallet.getModel());
		}
		return "/member/withdraw";
	}
	
	@RequestMapping(value = "/ftl/setLoginPasswrod")
	public String setLoginPasswrod(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		return "/member/setLoginPasswrod";
	}

	@RequestMapping(value = "/ftl/setTransPassword")
	public String setTransPassword(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		return "/member/setTransPassword";
	}

	@RequestMapping(value = "/ftl/nameVerify")
	public String nameVerify(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		return "/member/nameVerify";
	}

	@RequestMapping(value = "/ftl/telephoneVerify")
	public String telephoneVerify(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		return "/member/telephoneVerify";
	}

	@RequestMapping(value = "/userCenter")
	public String login(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		InvestorEntity investor = modelResult.getModel();
		ModelResult<InvestorWalletEntity> wModelResult = investorWalletService.queryInvestorWallet(investor.getId());
		if (wModelResult.isSuccess()) {
			ViewContext.put("wallet", wModelResult.getModel());
		}
		ViewContext.put("member", investor);
		return "/member/index";
	}

	@RequestMapping(value = "/ajax/financial/details", method = RequestMethod.GET)
	public String ajaxFinancialDetails(HttpServletRequest request, int transType, PageResultVO page) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "";
		}
		if (transType == 0) {
			transType = -1;
		}
		InvestorEntity investor = modelResult.getModel();
		ModelResult<PageResult<InvestorWalletFlowEntity>> pageResult = investorWalletService
				.queryInvestorWalletFlowByPage(investor.getId(), transType, page.getPageSize(), page.getPageIndex());
		if (pageResult.isSuccess()) {
			ViewContext.put("result", pageResult.getModel());
		}
		List<Object[]> transTypeData = selectDataService.getDataSouce("trans_type", null);
		ViewContext.put("transTypeList", transTypeData);
		return "/investor/financialDetailsDIV";
	}

	@RequestMapping(value = "/submit/nameVerify")
	public String submitNameVerify(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		InvestorEntity investor = modelResult.getModel();
		if (investor.getIsRealname() == InvestorEntity.IS_REALNAME_YES) {
			logger.info("用户已经通过实名认证，无需认证,investorId:{},account:{}", investor.getId(), investor.getAccount());
			ViewContext.put("errorMsg", "用户已经通过实名认证，无需认证");
			return "redirect:/member/ftl/nameVerify";
		}
		InvestorEntity updateObj = new InvestorEntity();
		updateObj.setId(investor.getId());
		updateObj.setIsRealname(InvestorEntity.IS_REALNAME_YES);
		ModelResult<Boolean> result = investorService.updateInvestor(updateObj);
		InvestorBankEntity investorBank=new InvestorBankEntity();
		investorBank.setId(investor.getBankRequestno());
		investorBank.setBankStatus(InvestorBankEntity.BANK_STATUS_YES);
		ModelResult<Boolean> ibankResult = investorBankService.updateInvestorBank(investorBank);
		if (result.isSuccess() && ibankResult.isSuccess()) {
			loginRestController.resetLoginInfo(request);
			return "redirect:/member/ftl/set";
		}
		ViewContext.put("errorMsg", "用户实名认证失败，请联系管理员");
		return "redirect:/member/ftl/nameVerify";
	}

	@RequestMapping(value = "/submit/setLoginPasswrod")
	public String submitLoginPasswrod(HttpServletRequest request, String oldPW, String newPW, String newRepreatPW) {
		if (oldPW.isEmpty() || newPW.isEmpty()) {
			logger.info("修改用户登录密码失败，参数不能为空,oldPW:{},newPW:{}", oldPW, newPW);
			ViewContext.put("errorMsg", "修改用户登录密码失败，参数不能为空");
			return "redirect:/member/ftl/setLoginPasswrod";
		}
		if (!newPW.equals(newRepreatPW)) {
			logger.info("用户登录密码输入不一致,pw:{},repeatPW:{}", newPW, newRepreatPW);
			ViewContext.put("errorMsg", "用户登录密码输入不一致");
			return "redirect:/member/ftl/setLoginPasswrod";
		}
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		InvestorEntity investor = modelResult.getModel();
		if (!investor.getPassword().equals(oldPW)) {
			logger.info("用户原始登录密码错误,oldPW:{},newPW:{}", oldPW, newPW);
			ViewContext.put("errorMsg", "用户原始登录密码错误");
			return "redirect:/member/ftl/setLoginPasswrod";
		}
		InvestorEntity updateObj = new InvestorEntity();
		updateObj.setId(investor.getId());
		updateObj.setPassword(newPW);
		ModelResult<Boolean> result = investorService.updateInvestor(updateObj);
		if (result.isSuccess()) {
			loginRestController.resetLoginInfo(request);
			return "redirect:/member/ftl/set";
		}
		ViewContext.put("errorMsg", "登录密码修改失败，请联系管理员");
		return "redirect:/member/ftl/setLoginPasswrod";
	}

	@RequestMapping(value = "/submit/setTransPassword")
	public String submitTransPassword(HttpServletRequest request, String erifyCode, String pw, String repeatPW) {
		if (erifyCode.isEmpty() || pw.isEmpty() || repeatPW.isEmpty()) {
			logger.info("修改用户交易密码失败，参数不能为空,erifyCode:{},pw:{},repeatPW:{}", erifyCode, pw, repeatPW);
			ViewContext.put("errorMsg", "修改用户交易密码失败，参数不能为空");
			return "redirect:/member/ftl/setTransPassword";
		}
		// TODO 手机短信 确认验证码
		if (!pw.equals(repeatPW)) {
			logger.info("用户交易密码输入不一致,pw:{},repeatPW:{}", pw, repeatPW);
			ViewContext.put("errorMsg", "用户交易密码输入不一致");
			return "redirect:/member/ftl/setTransPassword";
		}
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		InvestorEntity investor = modelResult.getModel();
		InvestorEntity updateObj = new InvestorEntity();
		updateObj.setId(investor.getId());
		updateObj.setTradePassword(pw);
		ModelResult<Boolean> result = investorService.updateInvestor(updateObj);
		if (result.isSuccess()) {
			loginRestController.resetLoginInfo(request);
			return "redirect:/member/ftl/set";
		}
		ViewContext.put("errorMsg", "交易密码修改失败，请联系管理员");
		return "redirect:/member/ftl/setTransPassword";
	}

	@RequestMapping(value = "/submit/pay")
	public String submitPay(HttpServletRequest request, String amount) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		if (StringUtils.isBlank(amount)) {
			logger.info("充值金额，参数不能为空,amount:{}", amount);
			ViewContext.put("errorMsg", "充值金额，参数不能为空");
			return "/member/pay";
		}
		//TODO 设置最低充值金额
		if (new BigDecimal(amount).compareTo(BigDecimal.ZERO) <= 0) {
			logger.info("充值金额不能为0");
			ViewContext.put("errorMsg", "充值金额不能为0");
			return "/member/pay";
		}
		InvestorEntity investor = modelResult.getModel();
		ModelResult<Boolean> result = yeePayService.unSendBindPayRequest(amount, investor);
		if (result.isSuccess()) {
			return "/member/paySucceed";
		}
		ViewContext.put("errorMsg", result.getErrMsg());
		return "/member/pay";
	}
	
	@RequestMapping(value = "/submit/withdraw", method = RequestMethod.POST)
	public String submitWithdraw(HttpServletRequest request, String amount,String password) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return "redirect:/login/index";
		}
		if (StringUtils.isBlank(amount) || StringUtils.isBlank(password)) {
			logger.info("提款失败，参数不能为空,amount:{}", amount);
			ViewContext.put("errorMsg", "提款失败，参数不能为空");
			return "/member/withdraw";
		}
		//TODO 设置最低提款金额
		if (new BigDecimal(amount).compareTo(BigDecimal.ZERO) <= 0) {
			logger.info("提款金额不能为0");
			ViewContext.put("errorMsg", "提款金额不能为0");
			return "/member/withdraw";
		}
		InvestorEntity investor = modelResult.getModel();
		String pw=MD5.md5Encode(password.trim());
		if (!investor.getTradePassword().equals(pw)) {
			logger.info("交易密码不正确");
			ViewContext.put("errorMsg", "交易密码不正确");
			return "/member/withdraw";
		}
		BigDecimal drawMoney=new BigDecimal(amount);
		ModelResult<Boolean> result = investorWalletService.investorWalletWithdraw(investor, drawMoney);
		if (result.isSuccess()) {
			return "/member/withdrawSucceed";
		}
		ViewContext.put("errorMsg", result.getErrMsg());
		return "/member/withdraw";
	}
}
